import 'dart:convert';
import 'dart:typed_data';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:full_display/unit/http/response_type.dart';

import 'http_callback.dart';

/// dio配置类
class DioManager {
  static const baseUrl = "https://xxx"; // 正式环境

  static DioManager instance = DioManager._internal();
  Dio? _dio;
  final Map<String, dynamic> _headers = {
    /*"Content-Type": "application/x-www-form-urlencoded"*/
  };

  // 单例 私有化构造初始化dio
  DioManager._internal() {
    if (_dio == null) {
      BaseOptions options = BaseOptions(
          // baseUrl: baseUrl,
          contentType: Headers.multipartFormDataContentType,
          responseType: ResponseType.json,
          // receiveDataWhenStatusError: false,
          // headers: _headers,
          connectTimeout: const Duration(seconds: 60),
          receiveTimeout: const Duration(seconds: 60));
      _dio = Dio(options);
    }
    // _dio?.interceptors.add(HeaderInterceptor());
    // _dio?.interceptors.add(HttpLogInterceptor(
    //     requestHeader: true,
    //     dataEncode: true,
    //     logPrint: (log) => debugPrint(log)
    // ));

    /// 正式环境拦截日志打印
    if (!const bool.fromEnvironment("dart.vm.product")) {
      _dio?.interceptors
          .add(LogInterceptor(requestBody: true, responseBody: true));
    }
  }

  Future<Uint8List> imageToBytes(String imageUrl) async {
    var response = await _dio?.get(imageUrl,
        options: Options(responseType: ResponseType.bytes));
    return Uint8List.fromList(response?.data);
  }

  get header => _headers;

  /// 更新header
  updateHeader() {
    _dio?.options.headers = _headers;
  }

  /// 请求，返回的渲染数据 T
  /// method：请求方法，NWMethod.GET等
  /// path：请求地址
  /// params：请求参数
  /// success：请求成功回调
  /// error：请求失败回调
  Future<dynamic> request(String method, String path,
      {String? baseUrl,
      Map<String, dynamic>? params,
      data,
      ProgressCallback? onSendProgress, // 上传数据进度
      ProgressCallback? onReceiveProgress, // 接受数据进度
      QbResponseType? responseType,
      Success? onSuccess,
      Failure? onFailure}) async {
    try {
      Response? response = await _dio?.request(
        path,
        queryParameters: params,
        data: data,
        onSendProgress: onSendProgress,
        onReceiveProgress: onReceiveProgress,
        options: Options(method: method),
      );
      if (response != null) {
        debugPrint(
            "respones=========code=${response.statusCode},header=${response.headers['set-cookie']}");
        //var _data = response.data;
        var _data;
        if (response.data.runtimeType == String) {
          print("============>123===${path}");
          //转成map
          if (path == 'http://192.168.43.1:8092') {
            _data = {};
          } else {
            _data = jsonDecode(response.data);
          }
        } else {
          _data = response.data;
        }
        debugPrint("respones=========data=${_data}  ${responseType == null}");
        if (_data != null) {
          // var _tempData = _data.toString();
          //debugPrint('response========${_data['meta']},${_data['status']}');
          var res;
          bool suc = false;
          responseType = responseType ?? QbResponseType.status;
          switch (responseType) {
            case QbResponseType.status:
              debugPrint(
                  'response========${_data["status"]},${_data['content']}');
              if (_data['status'] == 200) {
                suc = true;
                res = _data["content"];
              } else {
                res = _data["message"];
              }
              break;
            case QbResponseType.meta:
              if (_data["meta"]["errMsg"].toString().toLowerCase() ==
                  "success") {
                suc = true;
                res = _data["data"];
              } else {
                res = _data["errMsg"];
              }
              break;
            case QbResponseType.errorCode:
              if (_data['success']) {
                suc = true;
                res = _data["content"];
              } else {
                res = _data["errorMsg"];
              }
              break;
            default:
              debugPrint("response========default:$_data");
              suc = true;
              res = _data;
              break;
          }
          if (suc) {
            onSuccess?.call(res);
            return {'type': 'success', 'content': res};
          } else {
            onFailure?.call(res);
            return {'type': 'failure', 'content': res};
          }
        }
      } else {
        // if (error != null) error(ErrorRes(code: -1, message: "未知错误"));
        onFailure?.call("未知错误");
      }
    } on DioError catch (e) {
      var errorData;
      debugPrint("response========error:${e.type}");
      switch (e.type) {
        case DioErrorType.cancel:
          errorData = {"content": "请求取消"};
          break;
        case DioErrorType.connectionTimeout:
          errorData = {"content": "连接超时"};
          break;
        case DioErrorType.sendTimeout:
          errorData = {"content": "请求超时"};
          break;
        case DioErrorType.receiveTimeout:
          errorData = {"content": "响应超时"};
          break;
          errorData = e.response?.data;
          break;
        case DioErrorType.unknown:
          errorData = {"content": "请求异常，检查网络是否正常"};
          break;
        default:
          debugPrint("response========error:${e.message}");
          errorData = {"content": e.message};
          break;
      }
      onFailure?.call(errorData);
      errorData['type'] = 'failure';
      return errorData;
    }
  }
}
